package edu.ccut.saturn.basevalidate.businessvalidate;

import java.util.Date;
import java.util.Map;

import edu.ccut.saturn.component.DateFormatManager;
import edu.ccut.saturn.component.DefaultSaturnValidate;
import edu.ccut.saturn.component.ValidateResult;

public class DateCompareValidate extends DefaultSaturnValidate {

	private static final String EQUALS = "==";// == //$NON-NLS-1$

	private static final String NON_EQUALS = "!=";// != //$NON-NLS-1$

	private static final String LESS_THEN = "<";// < //$NON-NLS-1$

	private static final String MORE_THEN = ">";// > //$NON-NLS-1$

	private static final String MORE_THEN_EQUALS = ">=";// > //$NON-NLS-1$

	private static final String LESS_THEN_EQUALS = "<=";// > //$NON-NLS-1$

	public void doValidate(Object value, Object[] args, ValidateResult result) {
		if (value != null && args.length >= 2) {
			boolean hasError = false;
			String exp = (String) args[0];
			Date origin = DateFormatManager.getDateTime(value.toString());
			Date param = DateFormatManager.getDateTime(args[1].toString());
			
			if (origin != null && param != null) {
				if (EQUALS.equals(exp)) {
					if (origin != param) {
						hasError = true;
					}
				} else if (LESS_THEN.equals(exp)) {
					if (origin.compareTo(param) >= 0) {
						hasError = true;
					}
				} else if (MORE_THEN.equals(exp)) {
					if (origin.compareTo(param) <= 0) {
						hasError = true;
					}
				} else if (NON_EQUALS.equals(exp)) {
					if (origin.compareTo(param) == 0) {
						hasError = true;
					}
				} else if (MORE_THEN_EQUALS.equals(exp)) {
					if (origin.before(param)) {
						hasError = true;
					}
				} else if (LESS_THEN_EQUALS.equals(exp)) {
					if (origin.after(param)) {
						hasError = true;
					}
				}
			}
			if (hasError == true) {
				Map<String, String> errorInfos = getErrorInfos();
				String errorKey = "_error_";
				String errorInfo = null;

				if (errorInfos != null) {
					errorInfo = errorInfos.get(errorKey);
				}
				result.addValidateError(errorInfo, value);
			}
		}
	}
}
